package com.qd.panda.service.stroke;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.domain.entity.stroke.UserStrokeDTO;
import com.qd.common.panda.domain.entity.stroke.WebUserStrokeDTO;
import com.qd.panda.mapper.stroke.UserStrokeMapper;
import com.qd.panda.model.UserStroke;
import com.qd.panda.service.park.CarParkDoorpostLoginService;
import com.qd.panda.service.park.CarParkService;
import com.qd.system.service.user.UserOperatorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * 用户行程
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserStrokeService extends BaseService<UserStrokeMapper, UserStroke> {

    private static final String PARK_ID = "park_id";
    private static final String PROCESS_STATUS = "process_status";
    private static final String PREFIX_ID = "panda_user_stroke_sid_{0}";

    private final CarParkService carParkService;
    private final CarParkDoorpostLoginService carParkDoorpostLoginService;

    private final RedisTemplateUtil<UserStroke> redisTemplateUtil;


    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeDTO save(UserStrokeDTO dto) {
        final UserStroke model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeDTO update(UserStrokeDTO dto) {
        final UserStroke historyModel = Optional.ofNullable(getById(dto.getSid())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserStroke model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param sid 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String sid) {
        final UserStroke model = Optional.ofNullable(getById(sid)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(sid)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserStrokeDTO dto) {
        final QueryWrapper<UserStroke> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param sid 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String sid) {
        boolean exists = false;
        if (StringUtils.hasLength(sid)) {
            final UserStroke model = getById(sid);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param sid 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStroke getById(String sid) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, sid);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(sid), UserStroke.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param sid 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeDTO getByIdDto(String sid) {
        return Optional.ofNullable(getById(sid)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStroke getOne(UserStrokeDTO dto) {
        final QueryWrapper<UserStroke> queryWrapper = createQueryWrapper(dto);
        UserStroke model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeDTO getOneDto(UserStrokeDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<UserStroke> getList(UserStrokeDTO dto) {
        final QueryWrapper<UserStroke> queryWrapper = createQueryWrapper(dto);
        final List<UserStroke> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserStrokeDTO> getListDto(UserStrokeDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserStrokeDTO> page(Page<UserStroke> page, UserStrokeDTO dto) {
        final QueryWrapper<UserStroke> queryWrapper = createQueryWrapper(dto, "us.");
        final IPage<UserStrokeDTO> iPage = baseMapper.page(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(d -> {
                    buildDisplay(d);
                    Optional.ofNullable(carParkDoorpostLoginService.getDoorpostMsg(d.getUserId())).ifPresent(d::setDoorpostName);
                }
        ));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<WebUserStrokeDTO> webPage(Page<WebUserStrokeDTO> page, UserStrokeDTO dto) {
        final QueryWrapper<UserStroke> queryWrapper = createQueryWrapper(dto, "us.");
        UserOperatorService.buildInSql(dto, queryWrapper);
        final IPage<WebUserStrokeDTO> iPage = baseMapper.webPage(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }


    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserStroke model) {
        if (null == model) {
            return;
        }
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getSid());
        redisTemplateUtil.deleteByKey(key);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserStrokeDTO modelToDto(UserStroke model) {
        if (null == model) {
            return null;
        }
        final UserStrokeDTO dto = new UserStrokeDTO();
        dto.setSid(model.getSid());
        dto.setNickName(model.getNickName());
        dto.setStartTime(model.getStartTime());
        dto.setAppointmentTime(model.getAppointmentTime());
        dto.setIntoTime(model.getIntoTime());
        dto.setOutTime(model.getOutTime());
        dto.setBillStartTime(model.getBillStartTime());
        dto.setBillEndTime(model.getBillEndTime());
        dto.setParkTime(model.getParkTime());
        dto.setAmount(model.getAmount());
        dto.setPayAmount(model.getPayAmount());
        dto.setOnLinePayAmount(model.getOnLinePayAmount());
        dto.setProcessStatus(model.getProcessStatus());
        dto.setTripStatus(model.getTripStatus());
        dto.setParkId(model.getParkId());
        dto.setPlateNumber(model.getPlateNumber());
        dto.setUserId(model.getUserId());
        dto.setTripType(model.getTripType());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserStroke dtoToModel(UserStrokeDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserStroke model = new UserStroke();
        model.setSid(dto.getSid());
        model.setNickName(dto.getNickName());
        model.setStartTime(dto.getStartTime());
        model.setAppointmentTime(dto.getAppointmentTime());
        model.setIntoTime(dto.getIntoTime());
        model.setOutTime(dto.getOutTime());
        model.setBillStartTime(dto.getBillStartTime());
        model.setBillEndTime(dto.getBillEndTime());
        model.setParkTime(dto.getParkTime());
        model.setAmount(dto.getAmount());
        model.setPayAmount(dto.getPayAmount());
        model.setOnLinePayAmount(dto.getOnLinePayAmount());
        model.setProcessStatus(dto.getProcessStatus());
        model.setTripStatus(dto.getTripStatus());
        model.setParkId(dto.getParkId());
        model.setPlateNumber(dto.getPlateNumber());
        model.setUserId(dto.getUserId());
        model.setTripType(dto.getTripType());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserStrokeDTO dto) {
        dto.setAmountDisplay(Optional.ofNullable(dto.getAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setPayAmountDisplay(Optional.ofNullable(dto.getPayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setOnLinePayAmountDisplay(Optional.ofNullable(dto.getOnLinePayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setParkIdDisplay(carParkService.idToDisplay(dto.getParkId()));
        dto.setProcessStatusDisplay(DisplayUtil.getProcessStatusDisplay(dto.getProcessStatus()));
        dto.setTripStatusDisplay(DisplayUtil.getTripStatusDisplay(dto.getTripStatus()));
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(WebUserStrokeDTO dto) {
        dto.setAmountDisplay(Optional.ofNullable(dto.getAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setPayAmountDisplay(Optional.ofNullable(dto.getPayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setOnLinePayAmountDisplay(Optional.ofNullable(dto.getOnLinePayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setParkIdDisplay(carParkService.idToDisplay(dto.getParkId()));
        dto.setProcessStatusDisplay(DisplayUtil.getProcessStatusDisplay(dto.getProcessStatus()));
        dto.setTripStatusDisplay(DisplayUtil.getTripStatusDisplay(dto.getTripStatus()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserStrokeDTO> modelToDtoList(List<UserStroke> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserStroke> dtoToModelList(List<UserStrokeDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserStroke> createQueryWrapper(UserStrokeDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserStroke> createQueryWrapper(UserStrokeDTO dto, String tableAlias) {
        final QueryWrapper<UserStroke> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias)) {
                if (tableAlias.charAt(tableAlias.length() - 1) != '.') {
                    tableAlias += ".";
                }
            }
            if (StringUtils.hasLength(dto.getParkId())) {
                queryWrapper.eq(tableAlias + PARK_ID, dto.getParkId());
            }
            if (StringUtils.hasLength(dto.getPlateNumber())) {
                queryWrapper.eq(tableAlias + "plate_number", dto.getPlateNumber());
            }
            if (StringUtils.hasLength(dto.getUserId())) {
                queryWrapper.eq(tableAlias + "user_id", dto.getUserId());
            }
            if (null != dto.getTripStatus()) {
                queryWrapper.eq(tableAlias + "trip_status", dto.getTripStatus());
            }
            if (null != dto.getProcessStatus()) {
                queryWrapper.eq(tableAlias + PROCESS_STATUS, dto.getProcessStatus());
            }
            List<Integer> processStatusList = dto.getProcessStatusList();
            if (null != processStatusList && !processStatusList.isEmpty()) {
                if (processStatusList.size() == 1) {
                    queryWrapper.eq(tableAlias + PROCESS_STATUS, processStatusList.get(0));
                } else {
                    queryWrapper.in(tableAlias + PROCESS_STATUS, processStatusList);
                }
            }
        }
        if (null == dto || null == dto.getProcessStatus()) {
            queryWrapper.orderByAsc(tableAlias + "start_time");
        } else {
            queryWrapper.orderByAsc(tableAlias + "into_time");
        }
        queryWrapper.orderByAsc(tableAlias + PARK_ID);
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     */
    public List<UserStroke> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserStroke> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserStroke::getSid).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    /**
     * 计算数量，包含了预约数量，场内车辆数，入场数，出场数
     *
     * @param parkId 停车场ID
     * @return 数量
     */
    public List<Map<String, Long>> getCount(String parkId) {
        return getBaseMapper().getCount(parkId);
    }


    /**
     * 获得进行中的行程
     *
     * @param dto 查询参数
     * @return 进行中的行程
     */
    @Transactional(readOnly = true)
    public UserStroke getProcessStroke(UserStrokeDTO dto) {
        QueryWrapper<UserStroke> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(dto.getUserId())) {
            queryWrapper.eq("user_id", dto.getUserId());
        }
        if (StringUtils.hasLength(dto.getParkId())) {
            queryWrapper.eq(PARK_ID, dto.getParkId());
        }
        if (null != dto.getTripStatus()) {
            queryWrapper.eq("trip_status", dto.getTripStatus());
        }
        if (null != dto.getTripType()) {
            queryWrapper.eq("trip_type", dto.getTripType());
        }
        queryWrapper.last("limit 1");
        queryWrapper.orderByDesc("start_time");
        final UserStroke userStroke = getOne(queryWrapper, false);
        queryWrapper.clear();
        return userStroke;
    }
}